using System.Collections;
using System.Web;
using System.Web.Caching;
using System.Xml;

namespace SouthernLand.Common
{
    public class ResourceManager
    {
        public static string GetString(string name)
        {
            try
            {
                // chi bat len khi chay thu nghiem
                HttpContext.Current.Cache.Remove("strLanguages");

                Hashtable resources = GetResource();

                if (resources[name] == null)
                {
                    return "[" + name + "]";
                }
                return (string)resources[name];
            }
            catch
            {
                return name;
            }
        }

        private static Hashtable GetResource()
        {
            Hashtable resources;
            string cacheKey = "strLanguages";
            if (HttpContext.Current.Cache[cacheKey] == null)
            {
                resources = new Hashtable();
                LoadResource(resources, cacheKey);
            }
            return (Hashtable)HttpContext.Current.Cache[cacheKey];
        }

        private static void LoadResource(Hashtable target, string cacheKey)
        {
            string filePath;
            if (Globals.LangVietNam())
                filePath = HttpContext.Current.Request.PhysicalApplicationPath + "//Languages//Languages.xml";
            else
                filePath = HttpContext.Current.Request.PhysicalApplicationPath + "//Languages//Languages_en.xml";
            var dp = new CacheDependency(filePath);
            var d = new XmlDocument();
            try
            {
                d.Load(filePath);
            }
            catch
            {
                return;
            }

            foreach (XmlNode n in d.SelectSingleNode("root").ChildNodes)
            {
                if (n.NodeType != XmlNodeType.Comment)
                {
                    if (target[n.Attributes["name"].Value] == null)
                        target.Add(n.Attributes["name"].Value, n.InnerText);
                    else
                        target[n.Attributes["name"].Value] = n.InnerText;
                }
            }

            HttpContext.Current.Cache.Insert(cacheKey, target);
        }
    }
}